import CryptoJS from 'crypto-js';
import { selfI18n } from '@/i18n/index.js';
import _ from 'lodash';
import {
    showServerError
} from './MessageDeal';
import appConfig from '../config';

const ServerLang = {};
let UnitMap = null;
let UnitTypeMap = null;

const key = CryptoJS.enc.Utf8.parse('whnccloudweb1234');
const iv = CryptoJS.enc.Utf8.parse('whnccloudweb1234');

export const decrypted = function (str) {
    const bytes = CryptoJS.AES.decrypt(str, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return bytes.toString(CryptoJS.enc.Utf8);
};

export const encrypted = function (str) {
    const srcs = CryptoJS.enc.Utf8.parse(str);
    const encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
};
export const ssm = function (data) {
    showServerError(data, this);
};

// app的插件编写 需要为插件编写install属性，类型为方法。其中可以编写全局方法，mixin,
// 自定义指令，以及实例方法
ServerLang.install = function (app, options) {
    // 1. 添加全局方法或属性
    app.myGlobalMethod = function () {
        // 逻辑...
    };
    app.config.globalProperties.$encrypted = encrypted;
    app.config.globalProperties.$decrypted = decrypted;
    // 根据后端返回的key 进行转译出对应的语言字段
    app.config.globalProperties.$sl = function (key) {
        return key ? selfI18n('message.' + key) : '';
    };
    app.config.globalProperties.$st = function (key, data) {
        return key ? selfI18n(key, data) : '';
    };
    app.config.globalProperties.$appInfo = function (key) {
        return {
            version: appConfig.version
        };
    };
    // app.config.globalProperties.$isNumber = function (value) {
    //     return Object.config.globalProperties.toString.apply(value) === Types.number;
    // };
    app.config.globalProperties.$isEmptyObject = function (value) {
        let t;
        for (t in value) {
            return !1;
        }
        return !0;
    };
    // 根据后端返回的错误数据返回对应的错误提示
    app.config.globalProperties.$ssm = function (data) {
        showServerError(data, this);
    };
    app.config.globalProperties.$getUnitMap = function () {
        const rule = JSON.parse(sessionStorage.getItem('formatTime'));
        const unit_map = {};
        Object.keys(rule).forEach((key) => {
            unit_map[key] = rule[key].unit;
        });

        return unit_map;
    };
    app.config.globalProperties.$getUnitTypeMap = function () {
        const rule = JSON.parse(sessionStorage.getItem('formatTime'));
        // const unit_map = {};
        // rule.forEach((item) => {
        //     unit_map[item.key] = {
        //         unit: item.unit,
        //         type: item.type
        //     }
        // })
        return rule;
    };
    // app.config.globalProperties.$getByteLen = function (val) {
    //     let len = 0;
    //     for (let i = 0; i < val.length; i++) {
    //         const a = val.charAt(i);
    //         if (a.match(/[^\x00-\xff]/gi) != null) {
    //             len += 2;
    //         } else {
    //             len += 1;
    //         }
    //     }
    //     return len;
    // };
    app.config.globalProperties.$AlarmMsgTs = function (alarm_msg, devicename) {
        let msg_array;
        if (alarm_msg !== undefined) {
            msg_array = alarm_msg.split('|');
            msg_array[0] = '[' + (devicename || msg_array[0]) + ']' + ' ';
            msg_array[1] = this.$st(msg_array[1]);
            return msg_array.join('');
        }
        return '';
    };
    app.config.globalProperties.$fileSizeFormat = function (size) {
        if (typeof size === 'undefined') return '';
        if (size / 1024 > 1) {
            if (size / (1024 * 1024) > 1) {
                return Math.round((size / (1024 * 1024)) * 100) / 100 + 'MB';
            }
            return Math.round((size / 1024) * 100) / 100 + 'KB';
        }
        return size + 'B';
    };
    app.config.globalProperties.$getTimelineData = function (timeline) {
        const g_timeline = _.cloneDeep(timeline);
        const compare = (obj1, Obj2) => {
            var val1 = this.$newdate(obj1._timeStamp).getTime();
            var val2 = this.$newdate(Obj2._timeStamp).getTime();
            if (val1 < val2) {
                return -1;
            } else if (val1 > val2) {
                return 1;
            }
            return 0;
        };

        g_timeline.value.sort(compare);
        const newObj = { value: [] };
        let today = this.$toDayDate();

        const morning = today;

        if (this.$newdate(g_timeline.value[0]._timeStamp) < morning) {
            // 凌晨
            today = today.toISOString();

            console.log('凌晨字符串', today);

            // var current = new Date().getTime() + 8 * 60 * 60 * 1000;
            // 然后转化为东八区，当前的时间;
            var currents = new Date().toISOString();
            const obj1 = {
                _timeStamp: today,
                _value: 'Offline'
            };
            const obj2 = {
                _timeStamp: currents,
                _value: ''
            };
            g_timeline.value = [];
            g_timeline.value.push(obj1);
            g_timeline.value.push(obj2);
        } else {
            // 把当前的时间戳压进去,
            const currents = new Date().toISOString();
            var b = {
                _timeStamp: currents,
                _value: ''
            };
            g_timeline.value.push(b);
        }

        // 判断是否在同一天
        // var data1 = g_timeline.value[0]._timeStamp.substring(0, 10);
        // var data2 = g_timeline.value[
        //   g_timeline.value.length - 1
        // ]._timeStamp.substring(0, 10);
        // 让不在一天以内的时间，统一到在一天以内，删除那些不在一天以内的元素；
        var time_diff1, time_diff2;
        // 把数组的时间差放进数组对象里；
        for (var i = 0; i < g_timeline.value.length - 1; i++) {
            var _1 = g_timeline.value[i];
            var _2 = g_timeline.value[i + 1];
            time_diff1 = this.$newdate(_1._timeStamp).getTime() / 1000;
            // 获取数组的第一个时间的毫秒数；
            // 第一个数据
            var obj0 =
            this.$newdate(g_timeline.value[0]._timeStamp).getTime() / 1000;
            time_diff2 = this.$newdate(_2._timeStamp).getTime() / 1000;
            var obj2 = {
                _timeStamp: time_diff2 - time_diff1,
                _value: _1._value,
                time: time_diff1 - obj0
            };
            newObj.value.push(obj2);
        }

        return newObj.value;
    };
    app.config.globalProperties.$CustomerOptLog = function (opt_log_obj) {
        const log_type = opt_log_obj.operatetype;
        const customername = opt_log_obj.customername;
        const operator = opt_log_obj.operator;
        switch (log_type) {
        case 'restore':
            return this.$st('customer_opt_log_recover', { customername });
        case 'add':
            return this.$st('customer_opt_log_add', { customername });
        case 'del':
            return this.$st('customer_opt_log_del', { customername });
        case 'exit':
            return this.$st('customer_opt_log_exit', { customername });
        case 'update':
            return this.$st('customer_opt_log_update', { operator });
        case 'import_1':
            return this.$st('customer_opt_log_import1');
        case 'import_2':
            return this.$st('customer_opt_log_import2');
        case 'import_3':
            return this.$st('customer_opt_log_import3');
        default:
            return '';
        }
    };
    /* eslint-disable */
    app.config.globalProperties.$getAlarmMsgTsByObject = function (alarm_object, devicename) {
        // const uuid = alarm_object.uuid;
        // const msgid = alarm_object.msgid;
        // const time_text = this.$st('time');
        // const time = alarm_object.timeStamp;
        let val = alarm_object.val;
        const param = alarm_object.para;
        const setval = alarm_object.set_value;
        const flag = alarm_object.flag;
        const type = alarm_object.type;
        const RatedTime = alarm_object.RatedTime;
        const nowvalue_i18n = this.$st('nowvalue');
        const setvalue_i18n = this.$st('setvalue');
        const leave_i18n = this.$st('rest_old');
        const exceed_old = this.$st('exceed_old');
        const haduse_i18n = this.$st('had_use');
        if (UnitMap === null) {
            UnitMap = this.$getUnitMap();
        }
        if (UnitTypeMap === null) {
            UnitTypeMap = this.$getUnitTypeMap();
        }

        const flagMap_0 = {
            0: 'IntelType_0_flag_0',
            1: 'IntelType_0_flag_1',
            2: 'IntelType_0_flag_2'
        };
        const flagMap_2 = {
            0: 'IntelType_2_flag_0',
            1: 'IntelType_2_flag_1',
            2: 'IntelType_2_flag_2'
        };
        const flagMap_4 = {
            0: 'IntelType_4_flag_0',
            1: 'IntelType_4_flag_1',
            2: 'IntelType_4_flag_2'
        };
        const allFlagMap = {
            flagMap_0,
            flagMap_2,
            flagMap_4
        };

        if (type !== undefined) {
            let result;
            switch (type) {
            case 0:
                val = Math.floor(val * 1000) / 1000;
                const val_text = UnitTypeMap[param].type === 'time' ? this.$getHourMinSec(val) : val + UnitMap[param];
                const setval_text = UnitTypeMap[param].type === 'time' ? this.$getHourMinSec(setval) : setval + UnitMap[param];
                result = flag === 0 ? (nowvalue_i18n + val_text) : (nowvalue_i18n + ': ' + val_text + ' / ' + setvalue_i18n + ': ' + setval_text);
                return ` ${this.$st(param)}${this.$st(allFlagMap['flagMap_' + type][flag])} ${result}`;
            case 4:
                // const status_val = param === 'WHstatus_ControllerMode' ? this.$st(covertCnToEnkey(val)) : val;
                const status_val = val;
                return `${this.$st(param)} : ${status_val} ${UnitMap[param]}`;
            case 2:
                const rest_rate = RatedTime - val;
                const rest_rate_desc = rest_rate > 0 ? leave_i18n : exceed_old;
                const rate_time = rest_rate >= 0 ? rest_rate : -rest_rate;
                return `${this.$st(param)} ${haduse_i18n} : ${this.$getHourMinSec(val)}, ${rest_rate_desc} ${this.$getHourMinSec(rate_time)}`;
            }
        }
    };
   /* eslint-disable */
    var secondToDate = function (result) {
        var h = Math.floor(result / 3600) === 0 ? '0' + ':' : Math.floor(result / 3600) + ':';
        var m = Math.floor((result / 60 % 60)) === 0 ? '0' + ':' : Math.floor((result / 60 % 60)) + ':';
        var s = Math.floor((result % 60));
        result = (h.length >= 3 ? h : '0' + h) + (m.length >= 3 ? m : '0' + m) + (s >= 10 ? s : '0' + s);
        return result;
    };
    // 格式化数据，给值添加单位
    app.config.globalProperties.$format = function (ar1, ar2) {
        let rule = JSON.parse(sessionStorage.getItem('formatTime'));
        const match = rule[ar1];
        if (match === undefined) {
            rule = null;
            return ar2;
        }
        if ((match && (match.type === 'time')) || (match && (match.type === 'time_wear'))) {
            const time = secondToDate(ar2);

            return time;
        } else if (ar1 === 'WHstatus_Efficiency') {
            return ar2;
        } else if (ar1 === 'WHstatus_HadCompletedPercent') {
            return Number(ar2).toFixed(2) + ' ' + match.unit;
        } else if (ar1 === 'WHstatus_FeedV') {
            return Number(ar2).toFixed(2) + ' ' + match.unit;
        } else {
            return match ? (ar2 + ' ' + match.unit).trim() : ar2;
        }
    };
};

export default ServerLang;
